<template>
  <div>
    <ay-aside :page-info="pageInfo" />
    <div class="app-container">
      <div class="filter-container">
        <el-button v-waves class="filter-item refresh-btn" icon="el-icon-refresh" @click="handleRefresh" />
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" :disabled="disabledDelBtn" @click="handleDelete(delIdArr)">
          删除
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="30"
        />
        <el-table-column label="#" align="center" width="80">
          <template slot-scope="{$index}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" min-width="80px">
          <template slot-scope="{row}">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="昵称" min-width="80px">
          <template slot-scope="{row}">
            <span >{{ row.nickName }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="所属角色" min-width="120px">
          <template slot-scope="{row}">
            <el-tag v-for="(item,index) in row.roleNameList" :key="index" style="margin-top:2px;margin-left: 10px;" effect="dark" type="">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" width="150px">
          <template slot-scope="{row}">
            <span>{{ row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" align="center" width="150px">
          <template slot-scope="{row}">
            <span>{{ row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status == 1? 'info': 'success'">
              {{ row.status == 0? '正常': '冻结' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="最后登录时间" align="center" width="300px">
          <template slot-scope="{row}">
              <span>{{ row.logintime }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="handleUpdate(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete([row.userId])" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pageTotal > 0" :total="pageTotal" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList" />

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="所属角色：" prop="roleid">
            <el-select v-model="temp.roleIdList" multiple placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in selectList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名：" prop="username">
            <el-input v-model="temp.username" placeholder="输入用户名称" />
          </el-form-item>
          <el-form-item label="联系方式：" prop="mobile">
            <el-input v-model="temp.mobile" placeholder="输入联系方式" />
          </el-form-item>
          <el-form-item label="邮箱地址：" prop="email">
            <el-input v-model="temp.email" placeholder="输入邮箱地址" />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="temp.password" type="password" placeholder="输入登录密码" />
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <template>
              <el-radio v-model="temp.status" :label="0">正常</el-radio>
              <el-radio v-model="temp.status" :label="1">冻结</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogDelVisible"
        width="30%"
      >
        <span>确定删除数据？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDelVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserList, saveUserInfo, updateUserInfo, deletUserInfo, selectRoleList } from '@/api/privilege'
import { deepClone } from '@/utils/index'
import waves from '@/directive/waves' // waves directive
import AyAside from '@/components/Aside'
import md5 from 'js-md5'
import Pagination from '@/components/Pagination'
export default {
  name: 'Personnel',
  components: { AyAside,Pagination },
  directives: { waves },
  filters: {},
  data() {
    // 手机号验证
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    // 密码验证
    var checkPwd = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    return {
      isClearable: true, // 下拉树可清空（可选）
      isAccordion: true, // 下拉树可收起（可选）
      props: { // 下拉树配置项（必选）
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: true
      },
      disabledDelBtn: true,
      dialogIconVisible: false,
      dialogDelVisible: false,
      pageInfo: {},
      list: null,
      listLoading: true,
      selectList: null,
      delIdArr: [],
      temp: {
        userId: undefined,
        roleIdList: [],
        username: '',
        email: '',
        mobile: '',
        password: '',
        status: 0
      },
      tableData: [],
      toggleSwitch: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        username: [{ required: true, message: '用户名称不能为空', trigger: 'change' }],
        nickname: [{ required: true, message: '昵称不能为空', trigger: 'change' }],
        mobile: [
          { required: true, validator: checkPhone, trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, validator: checkPwd, trigger: ['blur', 'change'] }
        ]
      },
      userName: '',
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0
    }
  },
  created() {
    this.getList()
    this.pageInfo = this.$route.meta
  },
  methods: {
    // 获取表格数据接口
    getList() {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        getUserList({
          userName: this.userName,
          createUserId: null,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }).then(response => {
          this.list = response.data.list
          this.pageTotal = response.data.total
          this.pageSize = response.data.pageSize
          this.pageNum = response.data.pageNum
          const cloneData = deepClone(this.list)
          selectRoleList({}).then((response) => {
            this.selectList = response.data
          })
          this.tableData = cloneData
          for (const i in this.tableData) {
            const roleIdListTemp = []
            const roleNameListTemp = []
            for (const j in this.tableData[i].sysRoleDTOList) {
              roleIdListTemp.push(this.tableData[i].sysRoleDTOList[j].roleId)
              roleNameListTemp.push(this.tableData[i].sysRoleDTOList[j].roleName)
            }
            this.tableData[i].roleIdList = roleIdListTemp
            this.tableData[i].roleNameList = roleNameListTemp
          }
          this.listLoading = false
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
            resolve(true)
          }, 500)
        }).catch(error => {
          this.$message({
            message: error,
            type: 'error'
          })
          reject(false)
        })
      }
      )
    },
    // 刷新
    async handleRefresh() {
      if (await this.getList()) {
        this.$message({
          message: '刷新成功',
          type: 'success'
        })
      }
    },
    // 新增操作
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 表格选中时触发
    handleSelectionChange(selection) {
      this.delIdArr = []
      if (selection.length) {
        this.disabledDelBtn = false
        for (const i in selection) {
          this.delIdArr.push(selection[i].userId)
        }
      } else {
        this.disabledDelBtn = true
      }
    },
    // 初始化表单
    resetTemp() {
      this.temp = {
        userId: undefined,
        roleIdList: [],
        username: '',
        email: '',
        mobile: '',
        password: '',
        status: 0
      }
    },
    // 新增数据接口
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp, 'temp')
          this.temp.password = md5(this.temp.password)
          saveUserInfo(this.temp).then((response) => {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 编辑操作
    handleUpdate(row) {
      console.log(row, 'rrr')
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.temp.password = null
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据接口
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.password !== null) {
            this.temp.password = md5(this.temp.password)
          }
          updateUserInfo(this.temp).then((response) => {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 删除操作
    handleDelete(idArr) {
      this.dialogDelVisible = true
      this.delIdArr = idArr
    },
    deleteData() {
      deletUserInfo(this.delIdArr).then(() => {
        this.dialogDelVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .el-table {
    .gray-row {
      color: #c2d2d2;
    }
  }
  .el-button--mini{
    padding: 7px;
  }
  .filter-container{
    .filter-item {
      margin-left: 0;
      &.refresh-btn{
        background-color: #030303;
        color: azure;
      }
    }
  }
}
</style>
